﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tilver.Api.Weixin.MP;
using Tilver.Api.Weixin.MP.CommonAPIs;
using Tilver.Api.Weixin.MP.Context;
using Tilver.Api.Weixin.MP.Entities;
using Tilver.Api.Weixin.MP.Entities.Menu;
using Weixin.MP.BLL.SysConfig;
using Weixin.MP.DAL.WeixinMP;
using Weixin.MP.UI;
using Weixin.MP.Web.Filters;

namespace Weixin.MP.Web.Controllers
{
    public class MenuController : BaseController
    {
        
        #region 显示菜单


        public ActionResult Index()
        {
            //appID wx29f5ab0da4326388 appsecret 4151a54b97098ff41f52d154562ac0d5  F42AF69AD17D45A5A679B4FC3A4DE497
            /*{"menu":{"button":
            [{"sub_button":[{"key":"31","type":"click","name":"生活播报"},{"key":"32","type":"click","name":"北京天气"}],"name":"天气服务"},{"key":"2","type":"click","name":"天气监控"}]}}
            */
            /*{"menu":{"button":
              [{"type":"click","name":"今日歌曲","key":"V1001_TODAY_MUSIC","sub_button":[]}, 
               {"type":"click","name":"歌手简介","key":"V1001_TODAY_SINGER","sub_button":[]},
               {"name":"菜单","sub_button":[
                 {"type":"view","name":"搜索","url":"http://www.soso.com/","sub_button":[]},
                 {"type":"view","name":"视频","url":"http://v.qq.com/","sub_button":[]},
                 {"type":"click","name":"赞一下我们","key":"V1001_GOOD","sub_button":[]}  ]
               }
              ]}}
            */
            var result = new List<WeixinMenu>();
            //先从数据库获取，如果不存在，就从微信服务器获取
            //var menuResult = new GetMenuResult();
            var sysBo = new SysConfigBO();
            var sysEo = sysBo.Get(Common.WeixinMenu);
            if (sysEo == null)
            {
                var token = this.GetWeixinAccessToken();
                var menuResult = CommonApi.GetMenu(token);
                var menuJson = Newtonsoft.Json.JsonConvert.SerializeObject(menuResult);
                var fullMenu = Newtonsoft.Json.JsonConvert.DeserializeObject<GetMenuResultFull>(menuJson);
                //将数据转换为List格式数据
                var buttons = fullMenu.menu.button;
                for (var i = 0; i < buttons.Count; i++)
                {
                    var button = buttons[i];
                    result.Add(new WeixinMenu()
                    {
                        id = i + 1,
                        parentId = 0,
                        level = 1,
                        key = button.key ?? string.Empty,
                        name = button.name ?? string.Empty,
                        type = button.type ?? string.Empty,
                        url = button.url ?? string.Empty
                    });
                    if (button.sub_button != null && button.sub_button.Count > 0)
                    {
                        //二级菜单
                        for (var j = 0; j < button.sub_button.Count; j++)
                        {
                            var subButton = button.sub_button[j];
                            result.Add(new WeixinMenu()
                            {
                                id = (i + 1) * 100 + j + 1,
                                parentId = i + 1,
                                level = 2,
                                key = subButton.key ?? string.Empty,
                                name = subButton.name ?? string.Empty,
                                type = subButton.type ?? string.Empty,
                                url = subButton.url ?? string.Empty
                            });
                        }
                    }
                }

                //将信息存入数据库
                sysBo.Add(new SysConfigEO()
                {
                    SysKey = Common.WeixinMenu,
                    SysType = SysConfigEO.SysTypeEnum.Sys,
                    SysValue = Newtonsoft.Json.JsonConvert.SerializeObject(result)
                });
            }
            else
            {
                result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeixinMenu>>(sysEo.SysValue);
            }
            return View(result);
        }
        #endregion
        #region 添加设置
        
        public ActionResult Add()
        {
            //获取菜单
            var menuList = new List<WeixinMenu>();
            var sysBo = new SysConfigBO();
            var sysEo = sysBo.Get(Common.WeixinMenu);
            if (sysEo != null)
            {
                menuList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeixinMenu>>(sysEo.SysValue);
            }
            ViewBag.MenuList = menuList;

            return View();
        }

        [HttpPost]
        [DwzJsonException]
        public ActionResult AddMenu(int weixinmenu_parentid, string weixinmenu_type, string weixinmenu_name, string weixinmenu_key, string weixinmenu_url)
        {
            /*
             目前自定义菜单最多包括3个一级菜单，每个一级菜单最多包含5个二级菜单。
             一级菜单最多4个汉字，二级菜单最多7个汉字，多出来的部分将会以“...”代替。
             请注意，创建自定义菜单后，由于微信客户端缓存，需要24小时微信客户端才会展现出来。
             建议测试时可以尝试取消关注公众账号后再次关注，则可以看到创建后的效果。
             */
            //获取菜单
            var menuList = new List<WeixinMenu>();
            var sysBo = new SysConfigBO();
            var sysEo = sysBo.Get(Common.WeixinMenu);
            if (sysEo != null)
            {
                menuList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeixinMenu>>(sysEo.SysValue);
            }

            //检查菜单是否合法
            var menuCount = menuList.Count(w => w.parentId == weixinmenu_parentid);
            if (weixinmenu_parentid == 0)
            {
                if (menuCount >= 3)
                {
                    return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
                            {
                                StatusCode = DwzStatusCode.Error,
                                Message = string.Format("操作失败：{0}", "自定义菜单最多包括3个一级菜单！")
                            }));
                }
                if (weixinmenu_name.Length() > 8)
                {
                    return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
                    {
                        StatusCode = DwzStatusCode.Error,
                        Message = string.Format("操作失败：{0}", "一级菜单最多4个汉字！")
                    }));
                }
            }
            if (weixinmenu_parentid > 0)
            {
                if (menuCount >= 5)
                {
                    return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
                            {
                                StatusCode = DwzStatusCode.Error,
                                Message = string.Format("操作失败：{0}", "一级菜单最多包含5个二级菜单！")
                            }));
                }
                if (weixinmenu_name.Length() > 14)
                {
                    return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
                    {
                        StatusCode = DwzStatusCode.Error,
                        Message = string.Format("操作失败：{0}", "二级菜单最多7个汉字！")
                    }));
                }
            }

            var m = menuList.OrderByDescending(c => c.id).FirstOrDefault();
            menuList.Add(new WeixinMenu()
            {
                id = m == null ? 1 : m.id + 1,
                key = weixinmenu_key,
                level = weixinmenu_parentid == 0 ? 1 : 2,
                name = weixinmenu_name,
                parentId = weixinmenu_parentid,
                type = weixinmenu_type,
                url = weixinmenu_url
            });
            //将修改的菜单保存到数据库
            sysBo.Update(Common.WeixinMenu, Newtonsoft.Json.JsonConvert.SerializeObject(menuList));
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
                            {
                                StatusCode = DwzStatusCode.Ok,
                                Message = string.Format("添加成功！"),
                                NavTabId = "Menu_List",
                                Rel = "",
                                CallbackType = "closeCurrent"
                            })); 
        }
        #endregion
        #region 修改菜单
        public ActionResult Edit(int id)
        {
            //获取菜单
            var menuList = new List<WeixinMenu>();
            var sysBo = new SysConfigBO();
            var sysEo = sysBo.Get(Common.WeixinMenu);
            if (sysEo != null)
            {
                menuList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeixinMenu>>(sysEo.SysValue);
            }

            if (!menuList.Any(w => w.id == id))
            {
                return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
                {
                    StatusCode = DwzStatusCode.Error,
                    Message = string.Format("操作失败：{0}", "您操作的菜单不存在！")
                }));
            }
            ViewBag.Menu = menuList.FirstOrDefault(w => w.id == id);
            ViewBag.MenuList = menuList;
            return View();
        }
        [HttpPost]
        [DwzJsonException]
        public ActionResult EditMenu(int weixinmenu_id, int weixinmenu_parentid, string weixinmenu_type, string weixinmenu_name, string weixinmenu_key, string weixinmenu_url)
        {
            /*
             目前自定义菜单最多包括3个一级菜单，每个一级菜单最多包含5个二级菜单。
             一级菜单最多4个汉字，二级菜单最多7个汉字，多出来的部分将会以“...”代替。
             请注意，创建自定义菜单后，由于微信客户端缓存，需要24小时微信客户端才会展现出来。
             建议测试时可以尝试取消关注公众账号后再次关注，则可以看到创建后的效果。
             */
            //获取菜单
            var menuList = new List<WeixinMenu>();
            var sysBo = new SysConfigBO();
            var sysEo = sysBo.Get(Common.WeixinMenu);
            if (sysEo != null)
            {
                menuList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeixinMenu>>(sysEo.SysValue);
            }
            //菜单是否存在
            if (!menuList.Any(w => w.id == weixinmenu_id))
            {
                return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
                {
                    StatusCode = DwzStatusCode.Error,
                    Message = string.Format("操作失败：{0}", "您操作的菜单不存在！")
                }));
            }
            //检查菜单是否合法
            if (weixinmenu_parentid == 0)
            {
                if (weixinmenu_name.Length() > 8)
                {
                    return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
                    {
                        StatusCode = DwzStatusCode.Error,
                        Message = string.Format("操作失败：{0}", "一级菜单最多4个汉字！")
                    }));
                }
            }
            if (weixinmenu_parentid > 0)
            {
                if (weixinmenu_name.Length() > 14)
                {
                    return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
                    {
                        StatusCode = DwzStatusCode.Error,
                        Message = string.Format("操作失败：{0}", "二级菜单最多7个汉字！")
                    }));
                }
            }

            //var editMenu = new WeixinMenu();
            //for (int i = 0; i < menuList.Count; i++)
            //{
            //    if (menuList[i].id == weixinmenu_id)
            //        editMenu = menuList[i];
            //}
            //editMenu = new WeixinMenu()
            //{
            //    id = weixinmenu_id,
            //    parentId = weixinmenu_parentid,
            //    level = weixinmenu_parentid == 0 ? 1 : 2,
            //    type = weixinmenu_type,
            //    key = weixinmenu_key,
            //    name = weixinmenu_name,
            //    url = weixinmenu_url
            //};
            var editMenu = menuList.FirstOrDefault(w => w.id == weixinmenu_id);
            if (editMenu != null)
            {
                editMenu.type = weixinmenu_type;
                editMenu.key = weixinmenu_key;
                editMenu.name = weixinmenu_name;
                editMenu.url = weixinmenu_url;
            };

            //将修改的菜单保存到数据库
            sysBo.Update(Common.WeixinMenu, Newtonsoft.Json.JsonConvert.SerializeObject(menuList));
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
            {
                StatusCode = DwzStatusCode.Ok,
                Message = string.Format("修改成功！"),
                NavTabId = "Menu_List",
                Rel = "",
                CallbackType = "closeCurrent"
            })); ;
        }
        #endregion
        #region 删除菜单
        [DwzJsonException]
        public ActionResult Delete(int id)
        {
            //获取菜单
            var menuList = new List<WeixinMenu>();
            var sysBo = new SysConfigBO();
            var sysEo = sysBo.Get(Common.WeixinMenu);
            if (sysEo != null)
            {
                menuList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeixinMenu>>(sysEo.SysValue);
            }
            //菜单是否存在
            if (!menuList.Any(w => w.id == id))
            {
                return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
                {
                    StatusCode = DwzStatusCode.Error,
                    Message = string.Format("操作失败：{0}", "您操作的菜单不存在！")
                }));
            }
            //如果是主菜单，则子菜单也会被一起删除
            var delSubMenuList = menuList.FindAll(w => w.parentId == id);
            foreach (var weixinMenu in delSubMenuList)
            {
                menuList.Remove(weixinMenu);
            }
            var delMenu = menuList.Find(w => w.id == id);
            menuList.Remove(delMenu);
            //将修改的菜单保存到数据库
            sysBo.Update(Common.WeixinMenu, Newtonsoft.Json.JsonConvert.SerializeObject(menuList));
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
            {
                StatusCode = DwzStatusCode.Ok,
                Message = string.Format("删除成功！"),
                NavTabId = "Menu_List",
                Rel = "",
                CallbackType = ""
            }));

        }
        #endregion
        #region 同步菜单到微信平台
        [DwzJsonException]
        public ActionResult Publish()
        {
            var token = GetWeixinAccessToken();
            //获取菜单
            //var menuList = new List<WeixinMenu>();
            var sysBo = new SysConfigBO();
            var sysEo = sysBo.Get(Common.WeixinMenu);
            if (sysEo == null)
            {
                return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
                {
                    StatusCode = DwzStatusCode.Error,
                    Message = string.Format("操作失败：{0}", "请先添加菜单！")
                }));
            }
            var menuList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeixinMenu>>(sysEo.SysValue);
            var fullMenu = new GetMenuResultFull();
            foreach (var menu in menuList.Where(c => c.parentId == 0))
            {
                var rootButton = new MenuFull_RootButton()
                    {
                        key = menu.key,
                        name = menu.name,
                        type = menu.type,
                        url = menu.url
                    };
                foreach (var submenu in menuList.Where(w => w.parentId == menu.id))
                {
                    if (rootButton.sub_button == null) rootButton.sub_button = new List<MenuFull_RootButton>();
                    rootButton.sub_button.Add(new MenuFull_RootButton()
                        {
                            key = submenu.key,
                            name = submenu.name,
                            type = submenu.type,
                            url = submenu.url
                        });
                }
                if(fullMenu.menu==null)fullMenu.menu = new MenuFull_ButtonGroup();
                if (fullMenu.menu.button == null) fullMenu.menu.button = new List<MenuFull_RootButton>();
                fullMenu.menu.button.Add(rootButton);
            }
            //重新整理按钮信息
            var bg = CommonApi.GetMenuFromJsonResult(fullMenu).menu;
            var result = CommonApi.CreateMenu(token, bg);
            if (result.errcode != ReturnCode.请求成功)
            {
                return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
                {
                    StatusCode = DwzStatusCode.Error,
                    Message = string.Format("操作失败：{0}", result.errmsg)
                }));
            }
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
            {
                StatusCode = DwzStatusCode.Ok,
                Message = string.Format("同步成功！")
            }));
        }

        #endregion

        public ActionResult GetToken(string appId, string appSecret)
        {
            try
            {
                if (!AccessTokenContainer.CheckRegistered(appId))
                {
                    AccessTokenContainer.Register(appId, appSecret);
                }
                var result = AccessTokenContainer.GetTokenResult(appId); //CommonAPIs.CommonApi.GetToken(appId, appSecret);
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                //TODO:为简化代码，这里不处理异常（如Token过期）
                return Json(new { error = "执行过程发生错误！" }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public ActionResult CreateMenu(string token, GetMenuResultFull resultFull)
        {
            try
            {
                //重新整理按钮信息
                var bg = CommonApi.GetMenuFromJsonResult(resultFull).menu;
                var result = CommonApi.CreateMenu(token, bg);
                var json = new
                {
                    Success = result.errmsg == "ok",
                    Message = result.errmsg
                };
                return Json(json);
            }
            catch (Exception ex)
            {
                var json = new { Success = false, Message = ex.Message };
                return Json(json);
            }
        }

        public ActionResult GetMenu()
        {
            var result = new List<WeixinMenu>();
            //先从数据库获取，如果不存在，就从微信服务器获取
            //var menuResult = new GetMenuResult();
            var sysBo = new SysConfigBO();
            var sysEo = sysBo.Get(Common.WeixinMenu);
            if (sysEo == null)
            {
                //从微信服务器获取
                if (!AccessTokenContainer.CheckRegistered(Common.AppId))
                {
                    AccessTokenContainer.Register(Common.AppId, Common.AppSecret);
                }
                var tokenResult = AccessTokenContainer.GetTokenResult(Common.AppId);
                var menuResult = CommonApi.GetMenu(tokenResult.access_token);
                var menuJson = Newtonsoft.Json.JsonConvert.SerializeObject(menuResult);
                var fullMenu = Newtonsoft.Json.JsonConvert.DeserializeObject<GetMenuResultFull>(menuJson);
                //将数据转换为List格式数据
                var buttons = fullMenu.menu.button;
                for (var i = 0; i < buttons.Count; i++)
                {
                    var button = buttons[i];
                    result.Add(new WeixinMenu()
                    {
                        id = i + 1,
                        parentId = 0,
                        level = 1,
                        key = button.key ?? string.Empty,
                        name = button.name ?? string.Empty,
                        type = button.type ?? string.Empty,
                        url = button.url ?? string.Empty
                    });
                    if (button.sub_button != null && button.sub_button.Count > 0)
                    {
                        //二级菜单
                        for (var j = 0; j < button.sub_button.Count; j++)
                        {
                            var subButton = button.sub_button[j];
                            result.Add(new WeixinMenu()
                            {
                                id = (i + 1) * 100 + j + 1,
                                parentId = i + 1,
                                level = 2,
                                key = subButton.key ?? string.Empty,
                                name = subButton.name ?? string.Empty,
                                type = subButton.type ?? string.Empty,
                                url = subButton.url ?? string.Empty
                            });
                        }
                    }
                }

                //将信息存入数据库
                sysBo.Add(new SysConfigEO()
                    {
                        SysKey = Common.WeixinMenu,
                        SysType = SysConfigEO.SysTypeEnum.Sys,
                        SysValue = Newtonsoft.Json.JsonConvert.SerializeObject(result)
                    });
            }
            else
            {
                result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeixinMenu>>(sysEo.SysValue);
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }
        //public ActionResult GetMenu(string token)
        //{
        //    var result = CommonApi.GetMenu(token);
        //    if (result == null)
        //    {
        //        return Json(new { error = "菜单不存在或验证失败！" }, JsonRequestBehavior.AllowGet);
        //    }
        //    return Json(result, JsonRequestBehavior.AllowGet);
        //}

        public ActionResult DeleteMenu(string token)
        {
            try
            {
                var result = CommonApi.DeleteMenu(token);
                var json = new
                {
                    Success = result.errmsg == "ok",
                    Message = result.errmsg
                };
                return Json(json, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                var json = new { Success = false, Message = ex.Message };
                return Json(json, JsonRequestBehavior.AllowGet);
            }
        }

    }
}
